package com.karrysong.blog_springboot.handle;

import com.alibaba.fastjson.JSON;
import com.karrysong.blog_springboot.entity.RequestRecord;
import com.karrysong.blog_springboot.service.RecordService;
import com.karrysong.blog_springboot.util.HttpContextUtils;
import com.karrysong.blog_springboot.util.IpUtils;
import com.karrysong.blog_springboot.vo.Result;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.logging.SimpleFormatter;

/**
 * @ClassName: LogAspect
 * @Author: KarrySong
 * @Date: 2022/8/7 9:45
 * @Description:
 */
@Component
@Aspect
@Slf4j
public class LogAspect {

    @Autowired
    private RecordService recordService;

    //@Pointcut("execution(com.karrysong.blog_springboot.controller.*.*)")
    @Pointcut("execution(* com.karrysong.blog_springboot.controller.*.*(..))")
    public void logPointCut() {
    }

    @Around("logPointCut()")
    public Object around(ProceedingJoinPoint point) throws Throwable {
        long beginTime = System.currentTimeMillis();
        //执行方法
        Object result = point.proceed();
        //执行时长(毫秒)
        long time = System.currentTimeMillis() - beginTime;
        //保存日志
        recordLog(point, beginTime, time);
        return result;
    }

    private void recordLog(ProceedingJoinPoint joinPoint, long beginTime, long time) {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        LogAnnotation logAnnotation = method.getAnnotation(LogAnnotation.class);
        log.info("=====================log start================================");
        if (logAnnotation != null){
            log.info("module:{}",logAnnotation.module());
            log.info("operation:{}",logAnnotation.operation());
        }

        Date date = new Date(beginTime);
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String format = simpleDateFormat.format(date);

        log.info("request time:{}", format);


        //请求的方法名
        String className = joinPoint.getTarget().getClass().getName();
        String methodName = signature.getName();
        String classMethod = className + "." + methodName + "()";
        log.info("request method:{}", classMethod);

        //请求的参数
        Object[] args = joinPoint.getArgs();
        String params = null;
        if (args != null && args.length > 0){
            if (args[0] instanceof MultipartFile){
                params = "image";
            }else {
                params = JSON.toJSONString(args[0]);
                log.info("params:{}",params);
            }
        }

        //获取request 设置IP地址
        HttpServletRequest request = HttpContextUtils.getHttpServletRequest();
        String ipAddr = IpUtils.getIpAddr(request);
        log.info("ip:{}", ipAddr);

        String browserName = IpUtils.getBrowserName(request);
        log.info("browser:{}", browserName);
        /*String browserVersion = IpUtils.getBrowserVersion(request);
        log.info("browserVersion:{}", browserVersion);*/
        String osName = IpUtils.getOsName(request);
        log.info("os:{}", osName);


        log.info("execute time : {} ms",time);
        log.info("=====================log end================================");

        RequestRecord requestRecord = new RequestRecord();
        requestRecord.setRequestIp(ipAddr);
        requestRecord.setBrowserInfo(browserName);
        requestRecord.setOsInfo(osName);
        requestRecord.setExecuteTime(time);
        requestRecord.setRequestTime(beginTime);
        requestRecord.setParams(params);
        requestRecord.setRequestMethod(classMethod);

        Result result = recordService.insertRecord(requestRecord);
        System.out.println(result);
    }

}

